<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/10
 * Time: 14:27
 */

namespace App\HttpController\Home;

use App\Enums\UrlEnums;
use App\Library\Auth;
use App\Utility\Curl;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use EasySwoole\Component\Pool\Exception\PoolEmpty;
use EasySwoole\Component\Pool\Exception\PoolException;
use EasySwoole\HttpClient\HttpClient;
use EasySwoole\MysqliPool\Mysql;

class League extends Base
{
    /**
     * 联赛列表
     * @return bool
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\OrderByFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function lol()
    {
        $db = Mysql::defer('mysql');
        $params = $this->request()->getQueryParams();
        if( isset($params['type']) && $params['type'] == 'recently' ){
            $status = [0,1];
        }else{
            $status = isset($params['status']) ? [$params['status']] : [0,1,2];
        }
        $page = $params['page'] ?? 1;
        $pageSize = $params['pageSize'] ?? 20;
        $sort = $params['sort'] ?? 'asc';
        $lists = $db->whereIn('status',$status)->orderBy('start_time',$sort)->get('siam_lolleague', [$pageSize * ($page  - 1), $pageSize]);
        $count = $db->whereIn('status',$status)->count('siam_lolleague');

        foreach ($lists as $k=>$v){
            $lists[$k]['start_time'] = $this->getMsecToMescdate($v['start_time']);
            $lists[$k]['end_time'] = $this->getMsecToMescdate($v['end_time']);
            $lists[$k]['team_ids'] = json_decode($v['team_ids'],true);
            $lists[$k]['prize_pool'] = null;
            $lists[$k]['location'] = $v['address'];
            unset($lists[$k]['address']);
        }

        return $this->writeJson(
            1,
            ['currentPage'=>$page,'total'=>$count,'data'=>$lists],
            '请求成功'
        );
    }

    /**
     * dota联赛列表
     * @return bool
     * @throws \EasySwoole\Component\Pool\Exception\PoolEmpty
     * @throws \EasySwoole\Component\Pool\Exception\PoolException
     * @throws \Throwable
     */
    public function dota()
    {
        $params = $this->request()->getQueryParams();
        $res = MysqlPool::invoke(function (MysqlObject $db)use($params){
            if( isset($params['type']) && $params['type'] == 'recently' ){
                $status = [0,1];
            }else{
                $status = isset($params['status']) ? [$params['status']] : [0,1,2];
            }
            $page = $params['page'] ?? 1;
            $pageSize = $params['pageSize'] ?? 20;
            $sort = $params['sort'] ?? 'asc';
            $lists = $db->whereIn('status',$status)->orderBy('start_time',$sort)->get('siam_dotaleague', [$pageSize * ($page  - 1), $pageSize]);
            $count = $db->whereIn('status',$status)->count('siam_dotaleague');
            foreach ($lists as $k=>$v){
                $lists[$k]['start_time'] = $this->getMsecToMescdate($v['start_time']);
                $lists[$k]['end_time'] = $this->getMsecToMescdate($v['end_time']);
                $lists[$k]['team_ids'] = json_decode($v['team_ids'],true);
                $lists[$k]['team_prize'] = json_decode($v['team_prize'],true);
                if($v['prize']){
                    $lists[$k]['prize_pool'] = $v['prize'];
                }else{
                    $lists[$k]['prize_pool'] = null;
                }

            }
            return ['currentPage'=>$page,'total'=>$count,'data'=>$lists];
        });
        return $this->writeJson(1,$res,'请求成功');
    }

    /**
     * csgo联赛
     * @return bool
     * @throws \EasySwoole\Component\Pool\Exception\PoolEmpty
     * @throws \EasySwoole\Component\Pool\Exception\PoolException
     * @throws \Throwable
     */
    public function csgo()
    {
        $params = $this->request()->getQueryParams();
        $res = MysqlPool::invoke(function (MysqlObject $db)use($params){

            if( isset($params['type']) && $params['type'] == 'recently' ){
                $status = [0,1];
            }else{
                $status = isset($params['status']) ? [$params['status']] : [0,1,2];
            }
            $page = $params['page'] ?? 1;
            $pageSize = $params['pageSize'] ?? 20;
            $sort = $params['sort'] ?? 'asc';
            $lists = $db->whereIn('status',$status)->orderBy('start_time',$sort)->get('siam_csgoleague', [$pageSize * ($page  - 1), $pageSize]);
            $count = $db->whereIn('status',$status)->count('siam_csgoleague');
            foreach ($lists as $k=>$v){
                $lists[$k]['start_time'] = $this->getMsecToMescdate($v['start_time']);
                $lists[$k]['end_time'] = $this->getMsecToMescdate($v['end_time']);
                $lists[$k]['team_ids'] = json_decode($v['team_ids'],true);
                $lists[$k]['prizes'] = json_decode($v['prizes'],true);
                $lists[$k]['map_pool'] = json_decode($v['map_pool'],true);
                if(!$v['prize_pool']){
                    $lists[$k]['prize_pool'] = null;
                }
            }
            return ['currentPage'=>$page,'total'=>$count,'data'=>$lists];
        });
        return $this->writeJson(1,$res,'请求成功');
    }

    /**
     * 王者荣耀联赛
     * @return bool
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\OrderByFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function kog()
    {
        $db = Mysql::defer('mysql');
        $params = $this->request()->getQueryParams();
        if( isset($params['type']) && $params['type'] == 'recently' ){
            $status = [0,1];
        }else{
            $status = isset($params['status']) ? [$params['status']] : [0,1,2];
        }
        $page = $params['page'] ?? 1;
        $pageSize = $params['pageSize'] ?? 20;
        $sort = $params['sort'] ?? 'asc';
        $lists = $db->whereIn('status',$status)->orderBy('start_time',$sort)->get('siam_kogleague', [$pageSize * ($page  - 1), $pageSize]);
        $count = $db->whereIn('status',$status)->count('siam_kogleague');

        foreach ($lists as $k=>$v){
            $lists[$k]['start_time'] = $this->getMsecToMescdate($v['start_time']);
            $lists[$k]['end_time'] = $this->getMsecToMescdate($v['end_time']);
            $lists[$k]['team_ids'] = json_decode($v['team_ids'],true);
            $lists[$k]['prize_pool'] = null;
            $lists[$k]['location'] = $v['address'];
            unset($lists[$k]['address']);
        }

        return $this->writeJson(
            1,
            ['currentPage'=>$page,'total'=>$count,'data'=>$lists],
            '请求成功'
        );
    }

    /**
     * 联赛基本信息
     * @return bool
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function baseInfo()
    {
        $params = $this->request()->getQueryParams();
        if( !isset($params['game']) || !$params['game'] ){
            return $this->writeJson(0,'','game参数为空');
        }
        if( !isset($params['league_id']) || !$params['league_id'] ){
            return $this->writeJson(0,'','league_id参数为空');
        }
        $table = "siam_{$params['game']}league";
        $db = Mysql::defer('mysql');
        $res = $db->where('league_id',$params['league_id'])->getOne($table);
        if( isset($res['team_prize']) ){
            $res['team_prize'] = json_decode($res['team_prize'],true);
        }
        $res['start_time'] = $this->getMsecToMescdate($res['start_time']);
        $res['end_time'] = $this->getMsecToMescdate($res['end_time']);
        $res['team_ids'] = json_decode($res['team_ids'],true);
        if( $params['game'] == 'lol' || $params['game'] == 'kog' ){
            $res['prize_pool'] = null;
            $res['location'] = $res['address'];
            unset($res['address']);
        }
        if( $params['game'] == 'csgo' ){
            if( !$res['prize_pool'] ){
                $res['prize_pool'] = null;
            }
            $res['organizer'] = '';
        }
        if( $params['game'] == 'dota' ){
            if( !$res['prize'] ){
                $res['prize_pool'] = null;
            }else{
                $res['prize_pool'] = $res['prize'];
            }
            unset($res['prize']);
        }
        if( $res['team_ids'] ){
            $teamTable = "siam_{$params['game']}teams";
            $teamLists = $db->whereIn('team_id',$res['team_ids'])->get($teamTable);
            $res['team_list'] = $teamLists;
        }
        return $this->writeJson(1,$res,'请求成功');
    }

    public function score()
    {
        $option = [
            'path'      => UrlEnums::LOL_LEAGUE_BOARD_PATH,
            'api_time'  => $this->getMillisecond()
        ];
        $db = Mysql::defer('mysql');
        $leagues = $db->get('siam_lolleague');
        $a = [];
        foreach ( $leagues as $k=>$league ){
            $params = [
                'query'     => [
                    'league_id' => $league['league_id'],
                    'version'   => 2
                ],
                'header'    => Auth::getInstance()->header($option),
            ];
            $boardUrl = UrlEnums::FJURL.UrlEnums::LOL_LEAGUE_BOARD_PATH.'?version=2&league_id='.$league['league_id'];
            $client = new HttpClient($boardUrl);
//            list($s1, $s2) = explode(' ', microtime());
//            $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
//            $option = [
//                'path'      => UrlEnums::LOL_LEAGUE_BOARD_PATH,
//                'api_time'  => $microtime
//            ];
//            $header = Auth::getInstance()->header($option);

            $client->setHeaders($params['header']);
            $response = $client->get();
            $data = $response->getBody();
            var_dump($data);return;

            $response = Curl::request('GET',UrlEnums::FJURL.UrlEnums::LOL_LEAGUE_BOARD_PATH,$params);
            $content = $response->getBody();
            $data = json_decode($content, true);
            var_dump($data);
            if( $data['code'] != 200 ){
                return $this->writeJson(1,$data,'请求成功1');
            }

        }
        return $this->writeJson(1,$a,'请求成功');
    }

    /**
     * 联赛比赛列表
     * @return bool
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \EasySwoole\Mysqli\Exceptions\WhereParserFail
     * @throws \Throwable
     */
    public function matchLists()
    {
        $game = $this->request()->getQueryParam('game');
        $league_id = $this->request()->getQueryParam('league_id');
        $start_date = $this->request()->getQueryParam('start_date');
        $end_date = $this->request()->getQueryParam('end_date');
        $sort = $this->request()->getQueryParam('sort') ? : 'asc';
        if( empty($game) || !$game ){
            return $this->writeJson(0,null,'缺少game参数！');
        }
        if( empty($league_id) || !$league_id ){
            return $this->writeJson(0,null,'缺少league_id参数！');
        }
        $startDate = $start_date ? $start_date : date('Y-m-d 00:00:00');
        $endDate = $end_date ? $end_date : date("Y-m-d 00:00:00",strtotime("+1 day"));
        $start_time = strtotime($startDate)*1000;
        $end_time = strtotime($endDate)*1000;
        $db = Mysql::defer('mysql');
        $table = "siam_{$game}matchs";
        $joinTable = "siam_{$game}teams";
        $lists = $db->where('m.league_id',$league_id)
            ->whereBetween('m.start_time',[$start_time,$end_time])
            ->join($joinTable.' as ta','m.team_a_id=ta.team_id','left')
            ->join($joinTable.' as tb','m.team_b_id=tb.team_id','left')
            ->orderBy('m.start_time',$sort)
            ->get($table.' as m',null,'m.bo,m.id,m.match_id,m.battle_ids,m.league_id,m.start_time,m.team_a_score,m.team_b_score,m.status,ta.name as team_a_name,ta.logo as team_a_logo,tb.name as team_b_name,tb.logo as team_b_logo');
        foreach ( $lists as $k=>$v ){
            $lists[$k]['start_time'] = $this->getMsecToMescdate($v['start_time']);
            $lists[$k]['battle_ids'] = json_decode($v['battle_ids'],true);
        }
        return $this->writeJson(1,$lists,'请求成功');
    }

    /**
     * 参赛队伍列表
     * @return bool
     */
    public function joinTeams()
    {
        $game = $this->request()->getQueryParam('game');
        $league_id = $this->request()->getQueryParam('league_id');
        if( !$game ){
            return $this->writeJson(0,null,'缺少game参数！');
        }
        if( !$league_id ){
            return $this->writeJson(0,null,'缺少league_id参数');
        }
        $table = "siam_{$game}league";
        try {
            $team_ids = MysqlPool::invoke(function (MysqlObject $db) use ($table, $league_id) {
                $team_ids = $db->where('league_id', $league_id)->getValue($table, 'team_ids');
                return json_decode($team_ids, true);
            });
            if( $team_ids ){
                $teams = MysqlPool::invoke(function (MysqlObject $db)use($team_ids,$game){
                    return $db->whereIn('team_id',$team_ids)->get('siam_'.$game.'teams');
                });
                return $this->writeJson(1,$teams,'请求成功');
            }else{
                return $this->writeJson(1,[],'请求成功');
            }
        } catch (PoolEmpty $e) {
            return $this->writeJson(0,null,$e->getMessage());
        } catch (PoolException $e) {
            return $this->writeJson(0,null,$e->getMessage());
        } catch (\Throwable $e) {
            return $this->writeJson(0,null,$e->getMessage());
        }
    }
}